<template>
  <div class="scoring-result-page">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <a-form
        layout="inline"
        :model="formSerchParams"
        @submit="doSerach"
        class="search-form"
      >
        <a-form-item field="resultName" label="结果名称" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.resultName"
            placeholder="请输入结果名称"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="appId" label="应用ID" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.appId"
            placeholder="请输入应用ID"
            class="search-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        :row-class="setRowClass"
        @page-change="onPageChange"
        row-key="id"
      >
        <!-- 结果图片 -->
        <template #resultPicture="{ record }">
          <a-image
            width="80"
            :src="record.resultPicture"
            :preview-props="{
              actionsLayout: [
                'rotateRight',
                'zoomIn',
                'zoomOut',
                'originalSize',
              ],
            }"
            class="result-image"
          />
        </template>

        <!-- 属性集合展示 -->
        <template #resultProp="{ record }">
          <a-popover position="right">
            <div class="prop-tags">
              <a-tag
                v-for="(item, index) in getFirstThreeProps(record.resultProp)"
                :key="index"
                size="small"
                color="arcoblue"
              >
                {{ item }}
              </a-tag>
              <a-tag v-if="getPropCount(record.resultProp) > 3" size="small">
                +{{ getPropCount(record.resultProp) - 3 }}
              </a-tag>
            </div>
            <template #content>
              <div class="full-props">
                <a-tag
                  v-for="(item, index) in parseProps(record.resultProp)"
                  :key="index"
                  size="small"
                  color="arcoblue"
                  class="prop-tag"
                >
                  {{ item }}
                </a-tag>
              </div>
            </template>
          </a-popover>
        </template>

        <!-- 时间格式化 -->
        <template #createTime="{ record }">
          <div class="time-cell">
            {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm") }}
          </div>
        </template>

        <!-- 操作列 -->
        <template #optional="{ record }">
          <a-popconfirm
            content="确定要删除该结果吗？"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button type="text" status="danger" shape="circle">
              <template #icon><icon-delete /></template>
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { API } from "@/api/typings";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import {
  deleteScoringResultUsingPost,
  listScoringResultByPageUsingPost,
} from "@/api/scoringResultController";

//初始化搜索条件(不应该被修改
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

//执行搜索
const doSerach = () => {
  serachParame.value = {
    ...initSearchParams,
    ...formSerchParams.value,
  };
};

const formSerchParams = ref<API.ScoringResultQueryRequest>({});

const serachParame = ref<API.ScoringResultQueryRequest>({
  ...initSearchParams,
});

const dataList = ref<API.ScoringResult[]>([]);

const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listScoringResultByPageUsingPost(serachParame.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败", res.data.message);
  }
};

/**
 * 当分页变化时， 触发页面的重新加载
 * @param page
 */
const onPageChange = (page: number) => {
  serachParame.value = {
    ...serachParame.value,
    current: page,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.ScoringResult) => {
  if (!record.id) {
    return;
  }

  const res = await deleteScoringResultUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    await loadData();
  } else {
    message.error("删除回答失败", res.data.message);
  }
};

// 解析属性集合
const parseProps = (propStr: string) => {
  try {
    return JSON.parse(propStr) || [];
  } catch {
    return [];
  }
};

// 获取前三个属性
const getFirstThreeProps = (propStr: string) => {
  return parseProps(propStr).slice(0, 3);
};

// 获取属性总数
const getPropCount = (propStr: string) => {
  return parseProps(propStr).length;
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 5,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 表格列配置
const columns = [
  {
    title: "结果名称",
    dataIndex: "resultName",
    width: 150,
    ellipsis: true,
  },
  {
    title: "结果描述",
    dataIndex: "resultDesc",
    width: 200,
    ellipsis: true,
  },
  {
    title: "属性集合",
    dataIndex: "resultProp",
    slotName: "resultProp",
    width: 220,
  },
  {
    title: "得分范围",
    dataIndex: "resultScoreRange",
    width: 120,
    align: "center",
  },
  {
    title: "结果图片",
    dataIndex: "resultPicture",
    slotName: "resultPicture",
    width: 100,
    align: "center",
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 150,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 80,
    align: "center",
  },
];
const data = reactive([]);
// 监听数据变化 ，用与触发页面数据加载
watchEffect(() => {
  loadData();
});
</script>

<style scoped>
.scoring-result-page {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 16px;
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  gap: 16px;
  align-items: flex-end;
}

.table-card {
  background: var(--color-bg-2);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.prop-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.full-props {
  max-width: 300px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.prop-tag {
  margin: 2px;
}

.time-cell {
  font-size: 12px;
  color: var(--color-text-3);
}

.result-image {
  border-radius: 4px;
  transition: transform 0.2s;
  cursor: zoom-in;
}

.result-image:hover {
  transform: scale(1.05);
}

.stripe-row {
  background-color: var(--color-fill-1);
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }
}
</style>
